from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import BadData


def generate_save_user_token(openid):
    """
    对openid进行加密
    生成保存用户数据的token
    :param openid: 用户的openid
    :return: token
    """
    # 创建序列化器对象
    serializer = Serializer(settings.SECRET_KEY, 600)
    data = {'openid': openid}
    # 调用序列化器的dumps
    token = serializer.dumps(data)
    # 把加密后的openid返回
    return token.decode()


def check_save_user_token(openid):
    """
    对加密的openid进行解密
    :param openid: openid
    :return: openid or None
    """
    # 创建序列化器对象
    serializer = Serializer(settings.SECRET_KEY, 600)
    try:
        # 调用loads方法对数据进行解密
        openid = serializer.loads(openid)
    except BadData:
        return None
    else:
        return openid
